#include "thread_pool.h"
#include "timer.h"

extern Time_Queue* queue;
extern int epfd;
//主线程调用:处理客户端发过来的消息
void handleMessage(int sockfd, task_queue_t * que)
{
    //消息格式：cmd content
    //1.1 获取消息长度
    int length = -1;
    int ret = recvn(sockfd, &length, sizeof(length));
    printf("recv length: %d\n", length);

    //1.2 获取消息类型
    int cmdType = -1;
    ret = recvn(sockfd, &cmdType, sizeof(cmdType));
    printf("recv cmd type: %d\n", cmdType);
    task_t *ptask = (task_t*)calloc(1, sizeof(task_t));
    ptask->peerfd = sockfd;
    ptask->type= cmdType;
    if(length > 0) {
        //1.3 获取消息内容
        ret = recvn(sockfd, ptask->data, length);
        if(ret > 0) {
            //往线程池中添加任务
            taskEnque(que, ptask);
        }
    } else if(length == 0){
        taskEnque(que, ptask);
    }
    //存日志
    syslog(LOG_INFO,"A request from client, cmdType: %d.",cmdType);

    if(ret == 0) {//连接断开的情况
        printf("\nconn %d is closed.\n", sockfd);
        delEpollReadfd(epfd, sockfd);
        close(sockfd);
        syslog(LOG_INFO, "A connection is down");
    }

    //针对于putsfile和getsfile的情况处理,关闭监听
    //因为不关的话后面发来的文件数据会被主线程当成命令
    if(cmdType == CMD_TYPE_PUTS || cmdType == CMD_TYPE_GETS){
        delEpollReadfd(epfd, sockfd);
    }
}

void doTask(task_t * task)
{
    assert(task);
    int uid = -1;
    getUserid(task->peerfd, &uid);
    if(uid != -1){
        update_node(queue, uid, task->peerfd);

    }else{
        printf("==========\n");
    }
    switch(task->type) {
    case CMD_TYPE_PWD:  
        pwdCommand(task);   break;
    case CMD_TYPE_CD:
        cdCommand(task);    break;
    case CMD_TYPE_LS:
        lsCommand(task);    break;
    case CMD_TYPE_MKDIR:
        mkdirCommand(task);  break;
    case CMD_TYPE_RMDIR:
        rmdirCommand(task);  break;
    case CMD_TYPE_RMFILE:
        rmfileCommand(task);  break;
    case CMD_TYPE_LOGIN1:
        loginCommand1(task); break;
    case CMD_TYPE_LOGIN2:
        loginCommand2(task); break;
    case CMD_TYPE_REG1:
        regCommand1(task); break;
    case CMD_TYPE_REG2:
        regCommand2(task); break;
    case CMD_TYPE_PUTS:
        putsCommand(task);  
        //打开文件监听
        addEpollReadfd(epfd, task->peerfd);
        break;
    case CMD_TYPE_GETS:
        getsCommand(task);  
        //打开文件监听
        addEpollReadfd(epfd, task->peerfd);
        break;
    case CMD_TYPE_NOTCMD:
        notCommand(task);   break;
    }
}

void notCommand(task_t * task)
{
    printf("execute not command.\n");
}

